﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;

public class PaintAssetEditor {

	public static string AssetBundleOutPath = "AssetBundle";

	public static string PaintAssetBundleOutPath = "PaintAssetBundle";

	public static string PaintPath = "Assets/PaintAsset/";

	private static int ResVersion = 1;

	private static string ZipFileName = "APaint.Zip";

	private static List<string> BundleNames = new List<string>() {
		"painttable", "paintsound", "Version.txt", "Update.txt"
	};

	[MenuItem ("Painter/服务器打包AssetBundle")]
	static void CreateServerAssetBundle ()
	{  
		CreateAssetBundle ("Android", BuildTarget.Android);

		string serverPath = "D:\\wamp\\www\\bear\\paint\\";
		CreateVersionFile ();
		CopyAssetBundlesToServer (serverPath);
		CreateUpdateFile (FileTools.CombinePath (serverPath, ResVersion.ToString()));
		CopyAssetBundlesTo(serverPath);
		FileTools.CopyFile(FileTools.CombinePath(SourcePath (), "Update.txt"), serverPath + "\\" + ResVersion + "\\Update.txt");

		AssetDatabase.Refresh();
		EditorUtility.DisplayDialog("提示", "打包AssetBundle完成！", "确定");
	}

	[MenuItem ("Painter/IOS服务器打包AssetBundle")]
	static void CreateServerIosAssetBundle ()
	{  
		//Debug.LogError (Application.dataPath);

		CreateAssetBundle ("IOS", BuildTarget.iOS);

		//string serverPath = "D:\\wamp\\www\\bear\\paint_ios\\";
		string serverPath = "/Users/xiaobai/Desktop/Bear/paint/";
		CreateVersionFile ();
		CopyAssetBundlesToServer (serverPath);
		CreateUpdateFile (FileTools.CombinePath (serverPath, ResVersion.ToString()));
		CopyAssetBundlesTo(serverPath);
		FileTools.CopyFile(FileTools.CombinePath(SourcePath (), "Update.txt"), serverPath + "/" + ResVersion + "/Update.txt");

		AssetDatabase.Refresh();
		EditorUtility.DisplayDialog("提示", "打包AssetBundle完成！", "确定");

	}

	[MenuItem ("Painter/本地打包AssetBundle")]
	static void CreateLocalAssetBundle ()
	{  
		CreateAssetBundle ("Android", BuildTarget.Android);

		string dPath = FileTools.CombinePath (Application.persistentDataPath, PaintAssetBundleOutPath);
		FileTools.CreateDirectory (dPath);
		CreateVersionFile ();
		CopyAssetBundleToLocal (dPath);
		CreateUpdateFile (dPath);
		FileTools.CopyFile(FileTools.CombinePath(SourcePath (), "Update.txt"), FileTools.CombinePath(dPath, "Update.txt"));

		AssetDatabase.Refresh();
		EditorUtility.DisplayDialog("提示", "打包AssetBundle完成！", "确定");
	}

	[MenuItem ("Painter/本地打包AssetBundle到StreamingAssertsPath")]
	static void CreateLocalAssetBundleToStreaming ()
	{  
		CreateAssetBundle ("Android", BuildTarget.Android);

		string dPath = FileTools.CombinePath (Application.streamingAssetsPath, PaintAssetBundleOutPath);
		FileTools.CreateDirectory (dPath);
		CreateVersionFile ();
		CopyAssetBundleToLocal (dPath);
		CreateUpdateFile (dPath);
		FileTools.CopyFile(FileTools.CombinePath(SourcePath (), "Update.txt"), FileTools.CombinePath(dPath, "Update.txt"));

		AssetDatabase.Refresh();
		EditorUtility.DisplayDialog("提示", "打包AssetBundle完成！", "确定");
	}

	static void CreateAssetBundle(string platformName, BuildTarget target) {
		SetAssetBundleName (PaintPath, BundleNames[0]);
		SetAssetBundleName (PaintPath, BundleNames[1]);
		SetAnimBundleName ();
		//删除所有未使用的assetBundle资产数据库名称
		AssetDatabase.RemoveUnusedAssetBundleNames();

		string outputPath = Path.Combine(AssetBundleOutPath,  platformName);
		FileUtil.DeleteFileOrDirectory(outputPath);
		if (!Directory.Exists (outputPath)) {
			Directory.CreateDirectory (outputPath);
		}
		BuildPipeline.BuildAssetBundles (outputPath, BuildAssetBundleOptions.UncompressedAssetBundle, target);
	}

	static void SetAnimBundleName() {
		string path = FileTools.CombinePath (PaintPath, "paintanim");
		string[] dirs = Directory.GetDirectories(path);
		for (int i = 0; i < dirs.Length; i++) {
			//Debug.LogError (dirs[i]);
			string name = dirs[i].Replace("\\", "/");
			//Debug.LogError (name);
			string nameB = FileTools.GetFullName (name);
			//Debug.LogError (nameB);
			BundleNames.Add (nameB);
			SetAssetBundleName (path, nameB);
		}
	}

	static void SetAssetBundleName(string dir, string nameBundle) {
		string[] files = Directory.GetFiles(FileTools.CombinePath(dir, nameBundle));
		for (int i=0; i<files.Length; i++) {
			string name = files[i].Replace("\\", "/");
			if (files[i].IndexOf (".meta") > 0)
				continue;
			var mi = AssetImporter.GetAtPath(name);
			if (mi != null) {
				mi.assetBundleName = nameBundle.ToLower();
			}
		}
	}

	static void CopyAssetBundlesTo(string outputPath)
	{
		//string outputFolder = AssetBundleUtility.GetPlatformName();

		//string source = Path.Combine(Path.Combine(System.Environment.CurrentDirectory, AssetBundleOutPath), outputFolder);
		//string zipOutPath = Path.Combine(Path.Combine(System.Environment.CurrentDirectory, AssetBundleOutPath), "Zip");
		string zipOutPath = Path.Combine(outputPath, ZipFileName);
//		if (!System.IO.Directory.Exists(source) )
//			Debug.Log("No assetBundle output folder, try to build the assetBundles first.");

		//ClearPath (outputPath);

		ZipUtils.CreateZipFile (zipOutPath, SourcePath(), BundleNames);

		//ZipUtils.UnZipFile (zipOutPath, outputPath);


//		string[] files = Directory.GetFiles(source);
//		for (int i = 0; i < files.Length; i++)
//		{
//			string fileName = Path.GetFileName(files[i]);
//			string filePath = destination+Path.DirectorySeparatorChar.ToString()+fileName;
//			//排除一些不需要的文件
//			if (fileName.IndexOf(AssetBundleUtility.GetPlatformName()) >= 0) {
//				//文件夹名称的AssetBundle排除
//				continue;
//			}
//			if (fileName.IndexOf(".meta") < 0 && fileName.IndexOf(".manifest") < 0 && BundleNames.Contains(fileName)) {
//				if (File.Exists(filePath)) File.Delete(filePath);
//				File.Copy(files[i], filePath);
//			}
//		}
	}

	static void CopyAssetBundlesToServer(string path) {
		FileTools.CreateDirectory (path);
		FileTools.CopyFile(FileTools.CombinePath(SourcePath (), "Version.txt"), FileTools.CombinePath(path,"Version.txt"));


		FileTools.CreateDirectory (FileTools.CombinePath(path,ResVersion.ToString()));
		string[] files = Directory.GetFiles(SourcePath());
		for (int i = 0; i < files.Length; i++) {
			string fileName = Path.GetFileName (files [i]);
			//if (fileName.IndexOf (AssetBundleUtility.GetPlatformName ()) >= 0 || fileName.IndexOf (".meta") >= 0 || fileName.IndexOf (".manifest") >= 0 || !BundleNames.Contains (fileName)) {
			//	//文件夹名称的AssetBundle排除
			//	continue;
			//}
			if (fileName == "Version.txt") {
				continue;
			}
			//FileTools.CopyFile(files[i], path + "\\" + ResVersion + "\\" + fileName);
			string dp = FileTools.CombinePath(FileTools.CombinePath(path,ResVersion.ToString()), fileName);
			ZipUtils.CompressFile(files[i], dp);
		}
	}

	static void CopyAssetBundleToLocal(string path) {
		FileTools.CreateDirectory (path);
		FileTools.CopyFile(FileTools.CombinePath(SourcePath (), "Version.txt"), FileTools.CombinePath(path,"Version.txt"));
		string[] files = Directory.GetFiles(SourcePath());
		for (int i = 0; i < files.Length; i++) {
			string fileName = Path.GetFileName (files [i]);
			//if (fileName.IndexOf (AssetBundleUtility.GetPlatformName ()) >= 0 || fileName.IndexOf (".meta") >= 0 || fileName.IndexOf (".manifest") >= 0 || !BundleNames.Contains (fileName)) {
			//	//文件夹名称的AssetBundle排除
			//	continue;
			//}
			if (fileName == "Version.txt") {
				continue;
			}
			FileTools.CopyFile(files[i], FileTools.CombinePath(path,fileName));
			//ZipUtils.CompressFile(files[i], path + "\\" + ResVersion + "\\" + fileName);
		}
	}

	static void ClearPath(string path) {
		if (FileTools.IsDirectoryExist (path)) {
			FileUtil.DeleteFileOrDirectory (path);
		}
		FileTools.CreateDirectory (path);
	}

	static string ZipOutPath() {
		return Path.Combine(Path.Combine(System.Environment.CurrentDirectory, AssetBundleOutPath), "Zip");
	}

	static string SourcePath() {
        //return Path.Combine(Path.Combine(System.Environment.CurrentDirectory, AssetBundleOutPath), AssetBundleUtility.GetPlatformName());
        return null;
	}

	static void CreateVersionFile() {
		string path = Path.Combine (SourcePath (), "Version.txt");
		using (StreamWriter streamWriter = new StreamWriter(path, false)) {
			streamWriter.WriteLine(ResVersion);
			streamWriter.Flush();
		}
	}

	static void CreateUpdateFile(string serverPath) {
		string path = Path.Combine (SourcePath (), "Update.txt");
		using (StreamWriter streamWriter = new StreamWriter(path, false)) {
			//string source = FileTools.CombinePath (serverPath, ResVersion.ToString());
			string[] files = Directory.GetFiles(serverPath);
			for (int i = 0; i < files.Length; i++) {
				string fileName = Path.GetFileName(files[i]);
				//if (fileName.IndexOf(AssetBundleUtility.GetPlatformName()) >= 0 || fileName.IndexOf(".meta") >= 0 || fileName.IndexOf(".manifest") >= 0 || !BundleNames.Contains(fileName)) {
				//	//文件夹名称的AssetBundle排除
				//	continue;
				//}
				if (fileName == "Version.txt" || fileName == "Update.txt") {
					continue;
				}
				string md5 = FileTools.GetMD5(Path.Combine (SourcePath (), fileName));
				string filePath = Path.Combine (serverPath, fileName);
				long size = FileTools.GetFileSize(filePath);
				string value = fileName + ";" + size + ";" + md5;
				streamWriter.WriteLine(value);
				streamWriter.Flush();
			}
		}
	}
}
